// rollup.config.js
import babel from "@rollup/plugin-babel";
import resolve from "@rollup/plugin-node-resolve";
import typescript from "@rollup/plugin-typescript";
import commonjs from "@rollup/plugin-commonjs";
import alias from "@rollup/plugin-alias";
import { fileURLToPath } from "url";
import * as path from "path";
import { terser } from "rollup-plugin-terser";
import json from "@rollup/plugin-json";
import dotenv from "dotenv";

// 加载 .env 文件中的环境变量
dotenv.config();
// __filename包含当前模块文件的绝对路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const pathResolve = (p) => path.resolve(__dirname, p);
export default () => {
  const config = {
    // input: './index.dev.ts',
    output: {
      format: "cjs", // 输出为 CommonJS 格式
    },

    plugins: [
      json(),
      alias({
        // entries: [{find: "/@/", replacement: "./src/"}],
        entries: {
          "#": pathResolve("src"),
          _: __dirname,
        },
      }),
      resolve(), // 解析模块路径
      commonjs(),
      babel({
        // 使用 Babel 进行代码转换
        babelHelpers: "bundled", // 可以选择将 Babel helper 函数内联到输出中
      }),
      typescript({
        // 这里可以放置 TypeScript 编译器的选项
        // 例如：target, module, strict, esModuleInterop 等
        // tsconfig: './tsconfig.json', // 使用现有的 tsconfig.json 文件
        compilerOptions: {
          esModuleInterop: true,
          // 其他配置...
        },
      }),
    ],
  };
  const env = process.env.NODE_ENV;
  if (env && env.trim() === "production") {
    if (process.env.APP_TERSER === "true") {
      config.plugins.push(terser());
    }
    config.output.file = `dist/${process.env.APP_NAME}.min.js`;
  } else {
    config.output.file = `dist/${process.env.APP_NAME}.js`;
  }
  config.input = "./index.ts";
  return config;
};
